package mail.client;

import mail.account.UserAccount;
import java.io.PrintStream;
import java.util.List;
import mail.attribute.MailItem;
import mail.server.MailServer;

/**
 * A class to model a simple email client. The client is run by a
 * particular user, and sends and retrieves mail via a particular server.
 * @author David J. Barnes and Michael Kolling
 * @version 2006.03.30
 */
public class MailClient {
    // The server used for sending and receiving.

    private MailServer server;
    // The user running this client.
    private UserAccount user;

    /**
     * Create a mail client run by user and attached to the given server.
     */
    public MailClient(MailServer server, String user) throws Exception {
        if (!server.existsAccountInServer(user)) {
            throw new Exception("User account invalid");
        }
        this.server = server;
        this.user = new UserAccount(user);
    }

    /**
     * Return the next mail item (if any) for this user.
     */
    public MailItem getNextMailItem() {
        return server.getNextMailItem(user);
    }

    /**
     * Print the next mail item (if any) for this user to the text 
     * terminal.
     */
    public void printNextMailItem() {
        MailItem item = server.getNextMailItem(user);
        if (item == null) {
            PrintStream outFile = System.out;
            outFile.println("No new mail.");
            return;
        }
        item.print();

    }

    public void sendMailItem(MailItem item) {
        server.post(item);
    }

    public List<MailItem> getAllMails() {
        return server.fetchMailsFromUser(user);
    }

    public void deleteMailItem(MailItem item) {
        server.deleteMail(user, item);
    }

    public void deleteAllMails() {
        server.deleteAllMailFromUser(user);
    }

    public MailServer getMailServer() {
        return server;
    }

    public UserAccount getUserAccount() {
        return user;
    }
}
